import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import VueSetupExtend from "vite-plugin-vue-setup-extend";
import { resolve } from "path";
import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
import monacoEditorPlugin from "vite-plugin-monaco-editor";
import { plugin as markdownPlugin, Mode } from "vite-plugin-markdown"; // 导入插件和 Mode 枚举
import { viteStaticCopy } from "vite-plugin-static-copy";
// import viteCompression from "vite-plugin-compression"; // 需要服务端配置gzip

// import { fileURLToPath, URL } from "node:url";
import fs from "fs";

// https://vitejs.dev/config/
export default defineConfig(({ command }) => {
  const optimizeDepsElementPlusIncludes = ["element-plus/es"];
  fs.readdirSync("node_modules/element-plus/es/components").map((dirname) => {
    fs.access(`node_modules/element-plus/es/components/${dirname}/style/css.mjs`, (err) => {
      if (!err) {
        optimizeDepsElementPlusIncludes.push(`element-plus/es/components/${dirname}/style/css`);
      }
    });
  });
  return {
    plugins: [
      vue(),
      VueSetupExtend(),
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      (monacoEditorPlugin as any).default({
        languageWorkers: ["editorWorkerService", "typescript", "json", "html"],
      }),
      markdownPlugin({
        mode: [Mode.MARKDOWN], // or 'html' if you want to render it as HTML directly
      }),
      command === "build" &&
        viteStaticCopy({
          targets: [
            { src: "src/project/html/**/*", dest: "src/project/html" },
            // 可以添加更多复制规则
          ],
        }),
      // viteCompression({
      //   verbose: true,
      //   disable: false,
      //   threshold: 1024, // 压缩前最小文件大小
      //   algorithm: "gzip", // 压缩算法
      //   deleteOriginFile: true, // 删除原始文件
      // }),
    ].filter(Boolean), // 移除任何可能的 false 或 undefined 值,
    resolve: {
      alias: {
        "@": resolve(__dirname, "./src"),
      },
    },
    // 允许 Vite 使用 ESM 兼容的方式解析一些依赖
    optimizeDeps: {
      include: ["monaco-editor", "optimizeDepsElementPlusIncludes"],
    },
    build: {
      target: "esnext", // 使用 ESM 模块目标
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: true,
          drop_debugger: true,
        },
      },
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: "modern-compiler", // or 'modern'
        },
      },
    },
  };
});
